package com.yunc.nio.server;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * @author taocongcong
 * @create 2019-03-11 11:33
 */
public class NIOClient {

    private final InetSocketAddress serverAddress = new InetSocketAddress("localhost", 8080);
    private Selector selector = null;
    private SocketChannel client = null;

    private String nickName = "";
    private Charset charset = Charset.forName("UTF-8");
    private static String USER_CONTENT_SPILIT = "#@#";

    public NIOClient() throws IOException {
        client = SocketChannel.open(serverAddress);
        client.configureBlocking(false);
        selector = Selector.open();
        client.register(selector, SelectionKey.OP_READ);
    }

    public void session(){
        new Reader().start();
        new Writer().start();
    }

    private class Writer extends Thread {
        public void run(){
            try {
                Scanner scan = new Scanner(System.in);
                while (scan.hasNextLine()) {
                    String line = scan.nextLine();
                    if("".equals(line)) continue; //不允许发空消息
                    if("".equals(nickName)) {
                        nickName = line;
                        line = nickName + USER_CONTENT_SPILIT;
                    } else {
                        line = nickName + USER_CONTENT_SPILIT + line;
                    }
                    //client既能写也能读，这边是写
                    client.write(charset.encode(line));
                }
                scan.close();
            } catch (IOException e) {

            }
        }
    }

    private class Reader extends Thread {
        public void run(){
            try {
                while (true) {
                    int readyChannels = selector.select();
                    if (readyChannels == 0) {
                        continue;
                    }
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        process(key);
                    }
                }

            } catch (IOException io) {

            }
        }

        private void process(SelectionKey key) throws IOException {
            if (key.isReadable()) {
                SocketChannel sc = (SocketChannel)key.channel();
                ByteBuffer buff = ByteBuffer.allocate(1024);
                String content = "";
                while (sc.read(buff) > 0) {
                    buff.flip();
                    content += charset.decode(buff);
                }
                if (StringUtils.equals("你的昵称已存在", content)) {
                    nickName = "";
                }
                System.out.print(content);
                key.interestOps(SelectionKey.OP_READ);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        new NIOClient().session();
    }

}
